package com.sitech.ibnms.c3p.quartz;

import com.sitech.ibnms.c3p.Application;
import com.sitech.ibnms.c3p.util.C3pConstants;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.ignite.Ignite;
import org.apache.ignite.lang.IgniteRunnable;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.quartz.TriggerBuilder.newTrigger;

/**
 * Created by leo on 15/5/6.
 * quartz触发
 */
public class StartMultiC3pTasksJob implements Job {
    private static Logger logger = LoggerFactory.getLogger(StartMultiC3pTasksJob.class);

    public static final String USER_ID = "USER_ID";
    public static final String TASK_LIST = "TASK_LIST";

    @Autowired
    private Ignite ignite;

    @Override
    public void execute(final JobExecutionContext context) throws JobExecutionException {
        ignite.compute().run(new IgniteRunnable() {
            @Override
            public void run() {
                try {
                    logger.debug("execute c3p task starting job [fireInstanceId={}, triggerName={}, fireTime={}, scheduledFireTime={}, " +
                                    "previousFireTime={}, nextFireTime={}, mergedJobDataMap={}]",
                            context.getFireInstanceId(),
                            context.getTrigger().getKey().getName(),
                            format(context.getFireTime()),
                            format(context.getScheduledFireTime()),
                            format(context.getPreviousFireTime()),
                            format(context.getNextFireTime()),
                            context.getMergedJobDataMap().getWrappedMap()
                    );
                    Map<String, Object> jobDataMap = context.getMergedJobDataMap().getWrappedMap();
                    String userId = (String) jobDataMap.get(USER_ID);
                    List<Pair<Integer, String>> taskList = (List<Pair<Integer, String>>) jobDataMap.get(TASK_LIST);
                    for (int i = 0; i < taskList.size(); i++) {
                        Pair<Integer, String> pair = taskList.get(i);
                        int secondsDelay = pair.getLeft();
                        String c3pTaskId = pair.getRight();
                        Trigger trigger = newTrigger()
                                .forJob(Application.<JobDetail>getBean("c3pTaskStartingJob"))
                                .withIdentity(context.getTrigger().getKey().getName(), "DELAY" + i + "$" + secondsDelay + "s@" + context.hashCode())
                                .startAt(DateUtils.addSeconds(context.getFireTime(), secondsDelay))
                                .usingJobData(StartC3pTaskJob.C3P_TASK_ID, c3pTaskId)
                                .usingJobData(StartC3pTaskJob.USER_ID, userId)
                                .usingJobData(StartC3pTaskJob.TASK_TITLE, "【自动调度任务】")
                                .build();
                        trigger.getJobDataMap().put(C3pConstants.JOB_EXECUTION_CONTEXT, context);
                        Application.<Scheduler>getBean("quartzScheduler").scheduleJob(trigger);
                    }
                } catch (Throwable t) {
                    logger.error(t.getMessage(), t);
                }
            }
        });
    }

    public String format(Date date) {
        return date == null ? null : DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
    }
}
